package com.skyworth.web.admin.menu.repository;

import com.skyworth.web.admin.menu.domain.MenuModel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by lxs on 2016/8/8.
 */
public interface MenuRepository extends PagingAndSortingRepository<MenuModel, Long> {

	@Transactional
	@Modifying
	@Query("update MenuModel m set m.removeFlag = 1 where m.id = ?1")
	public void logicDel(long id);

	@Query("SELECT CASE WHEN COUNT(m) > 0 THEN 'true' ELSE 'false' END FROM MenuModel m WHERE m.name = ?1 and m.removeFlag=0 and m.storeId=?2")
	boolean existByName(String name, long store_id);

	@Transactional
	@Modifying
	@Query("update MenuModel m set m.soldOut=?2 where m.id = ?1")
	public int updateSoldOut(long menuId, int flag);

	@Query("select menu from MenuModel menu where menu.storeId=?1 and menu.stopSale=0 and menu.removeFlag=0")
	Page<MenuModel> allValidMenu(long store_id, Pageable pageable);

	@Query("select count(menu) from MenuModel menu where menu.storeId=?1 and menu.categoryId=?2")
	public int getCategoryCount(long store_id, long categoryId);

	@Query("select menu from MenuModel menu where menu.categoryId=?1 and menu.storeId=?2 and  menu.stopSale=0 and menu.removeFlag=0")
	Page<MenuModel> findByCategoryId(long categoryId,long store_id, Pageable pageable);

	@Query("select menu from MenuModel menu where menu.categoryId=?1 and  menu.stopSale=0 and menu.removeFlag=0")
	List<MenuModel> findByCategoryId(long categoryId);

	@Query("select menu from MenuModel menu where menu.storeId=?1 and  menu.stopSale=0 and menu.removeFlag=0")
	List<MenuModel> findByStore(long storeId);


	@Query("select menu from MenuModel menu where menu.storeId=?1 and (menu.name like %?2% or menu.firstLetter like %?2%)")
	List<MenuModel> queryByParams(Long storeId, String param);

	@Query("SELECT CASE WHEN COUNT(m) > 0 THEN 'true' ELSE 'false' END FROM MenuModel m WHERE m.name = ?1 and m.id <> ?2 and m.removeFlag=0 and m.storeId=?3")
	boolean existMenu(String name, long id, long store_id);
}
